package model

import (
	"git.oschina.net/ant180/scan/config"
	"github.com/seefan/gossdb"
	ssdbconf "github.com/seefan/gossdb/conf"
)

type SSDB struct {
	conf   *config.SSDBConf
	pool   *gossdb.Connectors
	client *gossdb.Client
}

func (p *SSDB) connect() error {
	if p.pool != nil {
		client, err := p.pool.NewClient()
		if err == nil {
			return nil
		}
		p.client = client
	}
	sp, err := gossdb.NewPool(&ssdbconf.Config{Host: p.conf.Host, Port: p.conf.Port})
	if err != nil {
		return err
	}
	p.pool = sp

	p.client, err = sp.NewClient()
	if err == nil {
		return nil
	}

	return err
}

func NewSSDB(conf *config.SSDBConf) (*SSDB, error) {
	s := &SSDB{
		conf: conf,
	}

	err := s.connect()
	if err != nil {
		return nil, err
	}

	return s, nil
}

func (p *SSDB) Zset(setName, key string, score int64) error {
	err := p.client.Zset(setName, key, score)
	if err == nil {
		return nil
	}
	err = p.connect()
	if err != nil {
		return err
	}
	return p.client.Zset(setName, key, score)
}

func (p *SSDB) LPop(key string) (string, error) {
	val, err := p.client.Qpop(key, false)
	if err == nil {
		return val.String(), nil
	}
	err = p.connect()
	if err != nil {
		return "", err
	}
	val, err = p.client.Qpop(key, false)
	return val.String(), err
}
